package it.nola.soccer.adapter;

import it.nola.soccer.DbConst;
import it.nola.soccer.GoalEdit;
import it.nola.soccer.R;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.view.View;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class GoalAdapter extends SimpleCursorAdapter {

    GoalEdit activity;
    protected int[] myTo;
    protected String[] myFrom;

    public GoalAdapter(GoalEdit context, int layout, Cursor c, String[] from, int[] to) {
	super(context, layout, c, from, to);
	activity=context;
	myTo=to;
	myFrom=from;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
	final int count=myTo.length;
	final int[] from=findColumns(myFrom);
	final int[] to=myTo;
	Resources r=context.getResources();
	String text;
	for (int i=0; i<count; i++) {
	    final View v=view.findViewById(to[i]);
	    if (v!=null) {
		if (DbConst.goals.KEY_TEAM.equals(myFrom[i])) {
		    text=DbConst.HOME_TEAM==cursor.getInt(from[i]) ? activity.getTeam1Name().toString() : activity
			.getTeam2Name().toString();
		}
		else if (DbConst.goals.KEY_NAME_PLAYER.equals(myFrom[i])) {
		    text=cursor.getString(from[i]);
		    if (cursor.getInt(cursor.getColumnIndex(DbConst.goals.KEY_IS_AUTO))==1) {
			text+=" "+r.getString(R.string.short_own_goal);
		    }
		}
		else if (DbConst.goals.KEY_HALF.equals(myFrom[i])) {
		    text=r.getTextArray(R.array.halfs)[cursor.getInt(from[i])].toString();
		}
		else {
		    text=cursor.getString(from[i]);
		}
		if (v instanceof TextView) {
		    setViewText((TextView) v, text);
		}
		else if (v instanceof ImageView) {
		    setViewImage((ImageView) v, text);
		}
		else {
		    throw new IllegalStateException(v.getClass().getName()+" is not a "
			+" view that can be bounds by this SimpleCursorAdapter");
		}
	    }
	}
    }

    private int[] findColumns(String[] from) {
	int i;
	int count=from.length;
	int[] ret=new int[count];
	for (i=0; i<count; i++) {
	    ret[i]=super.getCursor().getColumnIndexOrThrow(from[i]);
	}
	return ret;

    }

}
